package com.cn.bcyp.api.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class SendPort {

	/**
	 * GET的方法提交
	 * 
	 * @param sturl
	 *            提交的地址及参数
	 * @param cookie
	 * @return 返回的response信息
	 */
	public static String sendGet(String requrl, String cookie) {
		URLConnection connection = null;
		BufferedReader reader = null;
		String respurl = null;
		try {
			URL url = new URL(requrl);
			connection = url.openConnection();
			connection.setRequestProperty("Cookie", cookie);
			connection.setDoInput(true);
			connection.setDoOutput(false);

			reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			String lines;
			StringBuffer linebuff = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				linebuff.append(lines);
			}
			respurl = linebuff.toString();
		} catch (Exception e) {
			System.out.println("getmethod 错误：" + e);
			e.printStackTrace();
		} finally {
			try {
				reader.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return respurl;
	}

	/**
	 * POST方法提交
	 */
	public static String sendPost(String url, String parameter, String cookies) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";

		try {
			URL realurl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) realurl.openConnection();

			if ("" != cookies) {
				conn.setRequestProperty("Cookie", cookies);
			}

			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("POST");
			conn.setUseCaches(false);
			out = new PrintWriter(conn.getOutputStream());
			out.print(parameter);
			Thread.sleep(1000);
			out.flush();
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

}
